package com.hm.cms.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hm.cms.auto.su.BaseDomain;
import com.hm.cms.def.AdvertSiteEnum;
import com.hm.cms.domain.AdvertDomain;
import com.hm.cms.domain.QAdvertDomain;
import com.hm.cms.repository.AdvertRepository;
import com.hm.cms.service.AdvertService;
import com.hm.cms.su.BeanUtil;
import com.hm.cms.vo.HcmsAdvertVo;
import com.hm.common.def.DataStatusDef;
import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.util.CommonUtil;
import com.hm.common.util.DateUtil;

/**
 * @author shishun.wang
 * @date 2017年10月21日 上午11:00:49
 * @version 1.0
 * @describe
 */
@Service
public class AdvertServiceImpl implements AdvertService {

	@Autowired
	private AdvertRepository advertRepository;

	@Override
	public void addAdvert(HcmsAdvertVo advertVo, String operationUserId) {
		if (CommonUtil.isAnyEmpty(advertVo.getAdEmployer(), advertVo.getAdvertSite(), advertVo.getValidDate())) {
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}

		AdvertDomain domain = new AdvertDomain();
		BeanUtil.copyProperties(advertVo, domain);
		BaseDomain.initBaseInfo(domain);
		domain.setValidDate(new Date(advertVo.getValidDate()));
		domain.setCreateUser(operationUserId);
		advertRepository.save(domain);
	}

	@Override
	public List<HcmsAdvertVo> loadPageAdvert(AdvertSiteEnum advertSite) {
		if (CommonUtil.isEmpty(advertSite)) {
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}
		QAdvertDomain qAdvertDomain = QAdvertDomain.advertDomain;

		List<HcmsAdvertVo> vos = new ArrayList<HcmsAdvertVo>();

		advertRepository.findAll(qAdvertDomain.status.eq(DataStatusDef.ENABLE).and(qAdvertDomain.advertSite.eq(advertSite))).forEach(advert -> {
			HcmsAdvertVo vo = new HcmsAdvertVo();
			BeanUtil.copyProperties(advert, vo);
			vo.setCreateTime(DateUtil.data2long(advert.getCreateTime()));
			vo.setValidDate(DateUtil.data2long(advert.getValidDate()));
			vos.add(vo);
		});

		return vos;
	}
}
